<?php

namespace app\admin\controller\integral;
use app\common\controller\Backend;
use fast\Office;
use think\Db;
use think\Cache;
/**
 * 外联积分
 * Author wujinjun
 * @icon fa fa-circle-o
 */
class Outreach extends Backend
{
    protected $model = null;
    //统计外联积分
    public function outrs($ids=null,$department=null)
    {
        if (!$ids) return false;
        $arr = $this->jifen($ids);
        //所属区域
        $quyu = TableListSqlQuery('Field'," `name` = '".$department."' ",'parentid','hdyj_auth_department');
        $this->view->assign('quyu',$quyu[0]['parentid']);
        //所属公司
        $this->view->assign('department',$department);
        //外联积分统计
        $this->view->assign('user_num',$arr[1]);
        //学校积分概况
        $this->view->assign('result',$arr[0]);
        return $this->view->fetch();
    }
    //外联分组排名
    public function rank($ids=null){
        if (!$ids) return false;
        $weekDb = new \app\admin\model\finance\extract\Week();
        $week = $weekDb->find($ids);
        //获取当前几组
        $inteInfo = Db::name("integral_group")->where(array('starttime'=>$week['start_time'],'endtime'=>$week['end_time']))->find();
        $data = unserialize($inteInfo['data']);

        $info['data']=$data;
        $arr=array();
        $sort = array();
        //查询外联积分
        if(!empty($data)){
            foreach ($data as $key=>$v){
                foreach ($v as $k=>$val){
                    $week_num = $weekDb->where(array('start_time'=>$week['start_time'],'end_time'=>$week['end_time'],'department'=>$val))->find();
                    $ids = $week_num['id'];
                    //获取外联积分
                    if($ids)
                    {
                        $user = $this->jifen($ids);
                        arsort($user[1]);
                        foreach($user[1] as $kes=>$vas){
                            $sort[$kes] = $vas;
                        }
                        if(isset($sort)){
                            $arr[$key][$val] = $sort;
                            unset($sort);
                        }
                    }

                }
            }
        }


        $this->assign('result',$arr);
        $this->assign("inteInfo",$inteInfo);
        //组数统计
        $this->assign('scount',count($data));
        return $this->view->fetch();
    }
    //外联积分汇总
    public function count_rank($ids=null){
        if (!$ids) return false;
        $weekDb = new \app\admin\model\finance\extract\Week();
        $week = $weekDb->find($ids);
        //获取当前几组
        $inteInfo = Db::name("integral_group")->where(array('starttime'=>$week['start_time'],'endtime'=>$week['end_time']))->find();
        $data = unserialize($inteInfo['data']);
        $arr=array();
        $sort = array();
        //查询外联积分
        if(!empty($data)){
            foreach ($data as $key=>$v){
                foreach ($v as $k=>$val){
                    $week_num = $weekDb->where(array('start_time'=>$week['start_time'],'end_time'=>$week['end_time'],'department'=>$val))->find();
                    $ids = $week_num['id'];
                    //获取外联积分
                    if($ids)
                    {
                        $user = $this->jifen($ids);
                        arsort($user[1]);
                        foreach($user[1] as $kes=>$vas){
                            $sort[$kes] = $vas;
                        }
                        if(isset($sort)){
                            $arr[$key][$val] = $sort;
                            unset($sort);
                        }

                    }

                }
            }
        }
        //拼装导出数据
        $user_info = array();
        $j=0;
        foreach ($arr as $ks=>$va){
            foreach ($va as $key=>$val){
                foreach ($val as $ke=>$ve){
                    $user_info[$j]['fenzu'] = $ks.'组';
                    //查询分区
                    $quyu = TableListSqlQuery('Field'," `id` = '".$key."' ",'parentid','hdyj_auth_department');
                    //查询所属公司
                    $user_info[$j]['gongsi'] = TableField('AuthDepartment','name',$key);
                    $user_info[$j]['quyu'] = TableField('AuthDepartment','name',$quyu[0]['parentid']);
                    $user_info[$j]['name'] = TableField('Admin','username',$ke,'userid');
                    $user_info[$j]['jifen'] = $ve;
                    $j++;
                }
            }

        }
        array_multisort(array_column($user_info,'jifen'),SORT_DESC,$user_info);
        foreach ($user_info as $keys=>$vals){
            $user_info[$keys]['keys'] = $keys+1;
        }
        $excel = new Office();
        //设置表头：
         $head = ['序号','所属分组', '市场', '所属区域', '外联', '积分'];
        //数据中对应的字段，用于读取相应数据：
        $keys = ['keys','fenzu', 'gongsi', 'quyu', 'name', 'jifen'];
        $excel->count_rank_execl('外联积分汇总表', $user_info, $head, $keys);
    }

    //外联积分
    public function jifen($ids=null)
    {
        //学校表数据信息
        $School = new \app\admin\model\finance\extract\School;
        //学校外联信息
        $dbSchD = new \app\admin\model\finance\extract\school\Data;
        //场次学校信息
        $values = $School->where(array('extract_week'=>$ids))->order('id asc')->select()->toArray();

        //学校外联信息
        foreach ($values as $k=>$v){
            //学校名称
            $school_xuexiao[$v['id']] = TableField('DataSchool','name',$v['school_id']);
            //场次学校类别
            $school_leibie[$v['id']] = $v['level'];
            //跑下学校积分
            $school_jifen[$v['id']] = $v['people_num']&&$v['coming_num']?($v['people_num']/$v['coming_num']*100):0;
            //发书数量
            $school_fashu[$v['id']] = $v['gift_books'];
            //来人数
            $school_lairen[$v['id']] = $v['people_num'];
            //城市地级定义
            $school_city[$v['id']] = $v['ranking_level'];
            //查询学校外联信息
            $user_info = $dbSchD->where(array('type'=>1,'extract_school'=>$v['id']))->field('userid,extract_school')->select()->toArray();
            foreach ($user_info as $key=>$val){
                $arr[] = $val;
            }
            //查询是否是新外联
            foreach ($arr as $keys=>$vals){
                $zhengshi = TableListSqlQuery('Field'," `userid` = '".$vals['userid']."' ",'is_zhengshi','hdyj_admin');
                $arr[$keys]['zhengshi'] = $zhengshi[0]['is_zhengshi'];
            }
            foreach ($arr as $ks=>$vs){
                $list = TableListSqlQuery('Field'," `extract_week` = '".$ids."' and  `userid` = '".$vs['userid']."' ",'into_one_29,extract_week','hdyj_finance_extract_user');
                //新外联加分
                if($vs['zhengshi']==1){
                    $arr[$ks]['new_integral'] = $list[0]['into_one_29']*5;
                }
                //发书来人率积分
                $num = $school_fashu[$vs['extract_school']] && $school_lairen[$vs['extract_school']] ? Rounding($school_lairen[$vs['extract_school']]/$school_fashu[$vs['extract_school']])*100 : 0;
                //销售率加分
                if($school_leibie[$vs['extract_school']] == "A"){
                    $arr[$ks]['school_order'] = $list[0]['into_one_29']*5;
                    if($num>30){
                        if(count($user_info)>1){
                            $arr[$ks]['school_fashu'] = $num/count($user_info);
                        }else{
                            $arr[$ks]['school_fashu'] = $num;
                        }
                    }
                    //A类学校奖励积分
                    if(count($user_info)>1){
                        $arr[$ks]['school_jiangli'] = $school_lairen[$vs['extract_school']]/10*2/count($user_info);
                    }else{

                        $arr[$ks]['school_jiangli'] = $school_lairen[$vs['extract_school']]/10*2;
                    }

                }elseif($school_leibie[$vs['extract_school']] == "B"){
                    $arr[$ks]['school_order'] = $list[0]['into_one_29']*10;
                    if($num>30){
                        if(count($user_info)>1){
                            $arr[$ks]['school_fashu'] = Rounding($num/3/count($user_info));
                        }else{
                            $arr[$ks]['school_fashu'] = Rounding($num/3);
                        }
                    }
                    $arr[$ks]['school_jiangli'] = 0;
                }elseif($school_leibie[$vs['extract_school']] == "C"){
                    $arr[$ks]['school_order'] = $list[0]['into_one_29']*20;
                    if($num>30){
                        if(count($user_info)>1){
                            $arr[$ks]['school_fashu'] = Rounding($num/2/count($user_info));
                        }else{
                            $arr[$ks]['school_fashu'] = Rounding($num/2);
                        }
                    }
                    $arr[$ks]['school_jiangli'] = 0;
                }else{
                    $arr[$ks]['school_order'] = 0;
                    $arr[$ks]['school_fashu'] = 0;
                    $arr[$ks]['school_jiangli'] = 0;
                }

                //跑下学校积分
                if(count($user_info)>1){
                    //跑下学校合跑平分积分
                    $arr[$ks]['school_jifen'] =  Rounding($school_jifen[$vs['extract_school']]/count($user_info));
                }else{
                    $arr[$ks]['school_jifen'] =  Rounding($school_jifen[$vs['extract_school']]);
                }
                //奖励积分
                if($school_city[$vs['extract_school']]){
                    $arr[$ks]['school_chengshi'] = $list[0]['into_one_29']*3;
                }else{
                    $arr[$ks]['school_chengshi'] = 0;
                }
            }


        }

        //生成外联信息
        $result = array();
        $user_num = array();
        if(isset($arr)){
            //外联单个积分统计
            foreach($arr as $a=>$b){
                //学校名称
                $result[$b['extract_school']]['school_name'] = $school_xuexiao[$b['extract_school']];
                //学校比例
                $result[$b['extract_school']]['xuexiao'] = Rounding($school_jifen[$b['extract_school']]).'%';
                //发书比例
                $result[$b['extract_school']]['fashu'] = $school_lairen[$b['extract_school']] && $school_fashu[$b['extract_school']]? (Rounding($school_lairen[$b['extract_school']]/$school_fashu[$b['extract_school']])*100).'%':'0%';
                //学校类别
                $result[$b['extract_school']]['leibie'] = $school_leibie[$b['extract_school']];
                //外联个人积分信息
                $result[$b['extract_school']]['user'][] = $b;
                //外联个人积分统计
                if(isset($user_num[$b['userid']])){
                    $user_num[$b['userid']] += ($b['new_integral']+$b['school_order']+$b['school_fashu']+$b['school_jiangli']+$b['school_jifen']+$b['school_chengshi']);
                }else{
                    $user_num[$b['userid']] = $b['new_integral']+$b['school_order']+$b['school_fashu']+$b['school_jiangli']+$b['school_jifen']+$b['school_chengshi'];
                }
                //跑学校来人百分比积分
                $result[$b['extract_school']]['lairen_jifen'] = array_sum(array_column($result[$b['extract_school']]['user'],'school_jifen'));
                //发书来人率积分
                $result[$b['extract_school']]['fashu_jifen'] = array_sum(array_column($result[$b['extract_school']]['user'],'school_fashu'));
                //新外联跑学校积分
                $result[$b['extract_school']]['new_integral'] = array_sum(array_column($result[$b['extract_school']]['user'],'new_integral'));
                //销售积分
                $result[$b['extract_school']]['order'] = array_sum(array_column($result[$b['extract_school']]['user'],'school_order'));
                //A类学校来人积分
                $result[$b['extract_school']]['jiafen'] = array_sum(array_column($result[$b['extract_school']]['user'],'school_jiangli'));
                //省会城市排名积分
                $result[$b['extract_school']]['city'] = array_sum(array_column($result[$b['extract_school']]['user'],'school_chengshi'));
            }
            //存储外联积分
            foreach ($user_num as $kal=>$vals){
                $integral = TableField('User','integral_otreach',$kal);
                if(empty($integral)){
                    Db::name('finance_extract_user')->where(array('extract_week'=>$ids,'userid'=>$kal))->update(['integral_otreach' =>$user_num[$kal]]);
                }
            }
        }


        return array($result,$user_num);
    }

}